<template>
  <div class="timing">
    <div
      v-if="timeConfig && tableColumMaps && tableColumMaps.head.length === 0"
      class="not-support"
    >
      该数据表不支持定时设置
    </div>
    <a-form
      v-else
      :form="form"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      @submit="handleSubmit"
    >
      <a-form-item label="是否开启定时同步">
        <a-switch
          v-decorator="[
            'needSchedule',
            {
              valuePropName: 'checked',
              initialValue: timeConfig.needSchedule,
            },
          ]"
          size="small"
        >
        </a-switch>
      </a-form-item>
      <a-form-item label="所依据的属性">
        <a-select
          v-decorator="[
            'incrementColumn',
            {
              rules: [{ required: true, message: '请选择' }],
              initialValue: timeConfig.incrementColumn
                ? timeConfig.incrementColumn
                : tableColumMaps.head[0].name,
            },
          ]"
          class="tag-field"
          size="small"
          placeholder="请选择"
          :disabled="notNeedSchedule(form)"
        >
          <a-select-option
            v-for="op in (tableColumMaps? tableColumMaps.head : [])"
            :key="op.name"
            >{{ op.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="更新频率">
        <div class="frequency">
          <span class="label">每</span>
          <a-select
            v-decorator="[
              'intervalOfHour',
              {
                rules: [{ required: true, message: '请选择频率' }],
                initialValue: timeConfig.intervalOfHour,
              },
            ]"
            class="fre-number"
            size="small"
            placeholder="请选择"
            :disabled="notNeedSchedule(form)"
          >
            <a-select-option v-for="i in 24" :key="i">{{ i }}</a-select-option>
          </a-select>
          <a-select
            v-decorator="[
              'scheduleType',
              {
                rules: [{ required: true, message: '请选择频率' }],
                initialValue: timeConfig.scheduleType,
              },
            ]"
            class="fre-unit"
            :class="{
              fix: scheduleType === TimeUnit.hour,
            }"
            size="small"
            placeholder="请选择"
            :disabled="notNeedSchedule(form)"
            @change="timingTypeUnitChange"
          >
            <a-select-option :key="TimeUnit.hour">小时</a-select-option>
            <a-select-option :key="TimeUnit.day">天</a-select-option>
            <a-select-option :key="TimeUnit.week">周</a-select-option>
          </a-select>
        </div>
      </a-form-item>
      <a-form-item label="开始日期">
        <a-date-picker
          v-decorator="[
            'beginDate',
            {
              rules: [{ required: true, message: '请选择' }],
              initialValue: moment(new Date()),
            },
          ]"
          placeholder="请选择"
          format="YYYY-MM-DD"
          size="small"
          :disabled="notNeedSchedule(form)"
        >
        </a-date-picker>
      </a-form-item>
      <a-form-item v-show="scheduleType === TimeUnit.day" label="设置时间">
        <a-select
          v-decorator="[
            'hourOfDay',
            {
              rules: [{ required: true, message: '请选择时间' }],
              initialValue: timeConfig.hourOfDay,
            },
          ]"
          size="small"
          style="width: 90px;"
          :disabled="notNeedSchedule(form)"
        >
          <a-select-option v-for="i in 24" :key="i - 1"
            >{{ i - 1 }}时
          </a-select-option>
        </a-select>
        <a-select
          v-decorator="[
            'minuteOfHour',
            {
              rules: [{ required: true, message: '请选择时间' }],
              initialValue: timeConfig.minuteOfHour,
            },
          ]"
          size="small"
          style="width: 90px;"
          :disabled="notNeedSchedule(form)"
        >
          <a-select-option v-for="i in 60" :key="i - 1"
            >{{ i - 1 }}分
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-show="scheduleType === TimeUnit.hour" label="设置时间">
        <a-select
          v-decorator="[
            'minuteOfHour',
            {
              rules: [{ required: true, message: '请选择时间' }],
              initialValue: timeConfig.minuteOfHour,
            },
          ]"
          size="small"
          style="width: 180px;"
          :disabled="notNeedSchedule(form)"
        >
          <a-select-option v-for="i in 60" :key="i - 1"
            >{{ i - 1 }}分
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-show="scheduleType === TimeUnit.week" label="设置时间">
        <a-select
          v-decorator="[
            'daysOfWeek',
            {
              rules: [{ required: true, message: '请选择时间' }],
              initialValue: timeConfig.daysOfWeek,
            },
          ]"
          size="small"
          style="width: 180px;"
          :disabled="notNeedSchedule(form)"
        >
          <a-select-option v-for="item in weekDays" :key="item.value"
            >{{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
import UserStore from '@/store/modules/user'
import moment from 'moment'
// import {isArray} from '@/util/data-view-table-helper'
// import { cloneDeep } from 'lodash'
import { getTablesHead } from '@/api/data'
import { cloneDeep } from 'lodash'

/** 关联自增字段可用类型 */
const associatedFieldTypes = new Set([
  'tinyint',
  'smallint',
  'mediumint',
  'int',
  'integer',
  'bigint',
  'float',
  'double',
  'decimal',
  'date',
  'time',
  'year',
  'datetime',
  'timestamp',
])

const defaultConfig: any = {
  beginDate: moment(new Date()),
  daysOfWeek: 'SUN',
  hourOfDay: 0,
  incrementColumn: '',
  minuteOfHour: 0,
  needSchedule: false,
  intervalOfHour: 1,
  scheduleType: 'day',
}

const TimeUnit = {
  hour: 'hour',
  day: 'day',
  week: 'week',
}

@Component({
  name: 'timing-setting-modal',
  components: {},
})
export default class HttpModal extends Vue {
  public scheduleType: string = TimeUnit.day

  public TimeUnit: any = TimeUnit

  @Prop({
    type: String,
    default() {
      return ''
    },
  })
  tableName!: object

  public notNeedSchedule(form: any) {
    if (form.getFieldValue('needSchedule') === undefined) {
      return !this.timeConfig.needSchedule
    }
    return !form.getFieldValue('needSchedule')
  }

  // 外部数据选中的表
  public get selectedTables() {
    return DataStore.selectedDatasetInfo.dataConfig.tableName
  }

  public get selectedDatasetConfig() {
    return DataStore.databaseConfig
  }

  public get selectedTableId() {
    return DataStore.selectedDatasetId
  }

  public get selectedDatasetInfo() {
    return cloneDeep(DataStore.selectedDatasetInfo)
  }

  public get dataConfig() {
    return DataStore.databaseConfig
  }

  public get scheduleList() {
    return DataStore.scheduleList
  }

  public get timeConfig() {
    if (this.selectedDatasetInfo && this.selectedDatasetInfo.scheduleConfig) {
      this.scheduleType = this.selectedDatasetInfo.scheduleConfig.scheduleType
      return this.selectedDatasetInfo.scheduleConfig
    }
    this.scheduleType = TimeUnit.day
    return defaultConfig
  }

  public get isSubmit() {
    return DataStore.isEditSubmit
  }

  @Watch('isSubmit', { immediate: true })
  async handleSubmit() {
    if (this.isSubmit) {
      console.log(this.form)
      this.form.validateFields(async (error: Error, values: any) => {
        // 通过测试后，点击确定会提交相应数据，并获取所有表
        if (!error) {
          const config =
            this.tableColumMaps.head.length !== 0
              ? {
                  beginDate: values.beginDate,
                  daysOfWeek: values.daysOfWeek,
                  hourOfDay: values.hourOfDay,
                  incrementColumn: values.incrementColumn,
                  intervalOfHour: values.intervalOfHour,
                  minuteOfHour: values.minuteOfHour,
                  needSchedule: values.needSchedule,
                  scheduleType: values.scheduleType,
                }
              : null
          const passData = {
            ...DataStore.databaseConfig,
            databaseName: this.selectedDatasetInfo.dataConfig.databaseName,
            datasetScheduleConfig: config,
            userId: UserStore.currentUser?.id,
            id: DataStore.selectedDatasetId,
            tableName: this.selectedTables,
          }
          await DataStore.updateDatabaseConfig(passData)
          await DataStore.queryDataset(this.selectedTableId)
          console.log(passData)
        } else {
          console.log('error:', error)
        }
      })
      DataStore.setIsEditSubmit(false)
    }
  }

  public tableColumMaps: any = { head: [] }

  // public mounted() {
  //   this.getTablesHeadData()
  // }

  // 获取表格数据
  public async getTablesHeadData() {
    const passData = {
      ...DataStore.databaseConfig,
      tableNames: [this.selectedTables],
    }

    getTablesHead({ data: passData }).then((response: any) => {
      console.log('get table head', response)
      if (response.data.code === 100) {
        // 过滤可用类型
        response.data.result.forEach((tableHeadInfo: any) => {
          const headSet = tableHeadInfo as any
          headSet.head = (headSet.head as Array<any>).filter((item) => {
            return associatedFieldTypes.has(item.type as string)
          })
          this.tableColumMaps.head = headSet.head
        })
      }
    })
  }

  // 当前表格
  public currentTable: string = ''

  // 监听选中的表
  @Watch('selectedTables', { immediate: true })
  public getSelectedTables(newValue: any) {
    if (this.dataConfig && typeof this.dataConfig === 'object') {
      this.currentTable = newValue
      if (!this.formMaps[newValue]) {
        this.formMaps[newValue] = this.$form.createForm(this, {
          name: newValue,
        })
      }
      this.getTablesHeadData()
    }
  }

  // 表单
  private formMaps: any = {}

  // 星期
  public weekDays: Array<any> = [
    {
      label: '星期一',
      value: 'MON',
    },
    {
      label: '星期二',
      value: 'TUE',
    },
    {
      label: '星期三',
      value: 'WED',
    },
    {
      label: '星期四',
      value: 'THU',
    },
    {
      label: '星期五',
      value: 'FRI',
    },
    {
      label: '星期六',
      value: 'SAT',
    },
    {
      label: '星期日',
      value: 'SUN',
    },
  ]

  public form: any

  // form
  public beforeCreate() {
    this.form = this.$form.createForm(this, {
      name: 'import_timing_setting_form',
    })
  }

  public get moment() {
    return moment
  }

  // 提交
  // public handleSubmit() {
  //   const tableNames = Object.keys(this.formMaps)
  //   const formDataMaps = {} as any
  //   Object.values(this.formMaps).forEach((form: any, index: number) => {
  //     let formData = form.getForm().getFieldsValue()
  //     if(Object.keys(formData).length === 0) {
  //       formData = cloneDeep(defaultFormData)
  //     }
  //     formDataMaps[tableNames[index]] = formData
  //   })
  //   this.$emit('submit', formDataMaps)
  // }

  // 时间单位变更事件
  public timingTypeUnitChange(value: string) {
    this.scheduleType = value
  }

  public get isClear() {
    return DataStore.isClearForm
  }

  @Watch('isClear')
  clearForm() {
    if (this.isClear) {
      console.log('time')
      this.form.resetFields()
      DataStore.setIsClearForm(false)

      // 每次重新打开重置needSchedule值
      this.form.setFieldsValue({
        needSchedule: this.timeConfig.needSchedule,
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .tag-field {
  width: 180px;
}

.frequency {
  /deep/ .ant-select {
    display: inline-block;
    width: 100px;

    // 时间频率数
    &.fre-number {
      margin: 0 10px;
      width: 60px;
    }

    // 时间单位
    &.fre-unit {
      width: 60px;

      &.fix {
        width: 64px;
      }

      .ant-select-selection {
        border-width: 0 !important;

        &:hover {
          border-width: 0 !important;
        }
      }

      .ant-select-selection__rendered {
        border-width: 0 !important;
      }

      .ant-select-arrow {
        right: 12px;

        .anticon {
          display: inline-block;

          &.anticon-down {
            border: 5px solid transparent;
            border-top-color: #888;
            height: 0;
            width: 0;
          }

          svg {
            display: none !important;
          }
        }
      }
    }
  }
}

.not-support {
  height: 197px;
  line-height: 197px;
  margin: auto;
  text-align: center;
  width: 100%;
}
</style>
